<template>
  <div class="meal-plan-container">
    <!-- 页面标题 -->
    <Card shadow style="margin-bottom: 20px;">
      <Row type="flex" justify="space-between" align="middle">
        <i-col span="12">
          <h2 style="margin: 0;">餐饮计划管理</h2>
        </i-col>
        <i-col span="12" style="text-align: right;">
          <Button type="primary" @click="showCreateModal">新增计划</Button>
        </i-col>
      </Row>
    </Card>

    <!-- 日期选择和筛选 -->
    <Card shadow style="margin-bottom: 20px;">
      <Row :gutter="20">
        <i-col :xs="24" :sm="12" :md="6">
          <label style="display: block; margin-bottom: 5px; font-weight: bold;">选择日期</label>
          <DatePicker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
            @on-change="onDateChange"
          ></DatePicker>
        </i-col>
        <i-col :xs="24" :sm="12" :md="6">
          <label style="display: block; margin-bottom: 5px; font-weight: bold;">餐次筛选</label>
          <Select v-model="filterMealType" clearable placeholder="请选择餐次">
            <Option value="breakfast">早餐</Option>
            <Option value="lunch">午餐</Option>
            <Option value="dinner">晚餐</Option>
          </Select>
        </i-col>
        <i-col :xs="24" :sm="12" :md="6">
          <label style="display: block; margin-bottom: 5px; font-weight: bold;">卡路里范围</label>
          <Input-Number
            v-model="filterCalorieMin"
            :min="0"
            :max="5000"
            placeholder="最小卡路里"
            style="width: 100%;"
          ></Input-Number>
        </i-col>
        <i-col :xs="24" :sm="12" :md="6">
          <label style="display: block; margin-bottom: 5px; font-weight: bold;">操作</label>
          <Button style="width: 100%; margin-right: 5px;" @click="searchMeals">查询</Button>
          <Button style="width: 100%;" @click="resetFilter">重置</Button>
        </i-col>
      </Row>
    </Card>

    <!-- 每日三餐展示 -->
    <div class="meals-wrapper">
      <!-- 早餐 -->
      <Card shadow class="meal-card breakfast-card" style="margin-bottom: 20px;">
        <Row type="flex" justify="space-between" align="middle" style="margin-bottom: 15px;">
          <i-col>
            <h3 style="margin: 0;">
              <Icon type="md-sunny" size="24" style="margin-right: 10px; color: #ff9800;"></Icon>
              <span>早餐</span>
              <Tag color="orange" style="margin-left: 10px;">07:00 - 09:00</Tag>
            </h3>
          </i-col>
          <i-col>
            <Button type="primary" size="small" @click="showCreateMealModal('breakfast')">添加早餐</Button>
          </i-col>
        </Row>
        <Divider style="margin: 15px 0;"></Divider>
        <div v-if="breakfastMeals.length > 0" class="meals-list">
          <div v-for="meal in breakfastMeals" :key="meal.id" class="meal-item">
            <MealCard :meal="meal" @edit="editMeal" @delete="deleteMeal"></MealCard>
          </div>
          <!-- 早餐统计 -->
          <div class="meal-summary">
            <Row :gutter="20">
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总热量：</span>
                  <span class="value">{{ breakfastCalories }} kcal</span>
                </div>
              </i-col>
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总蛋白质：</span>
                  <span class="value">{{ breakfastProtein }}g</span>
                </div>
              </i-col>
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总脂肪：</span>
                  <span class="value">{{ breakfastFat }}g</span>
                </div>
              </i-col>
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总碳水：</span>
                  <span class="value">{{ breakfastCarbs }}g</span>
                </div>
              </i-col>
            </Row>
          </div>
        </div>
        <div v-else class="empty-meal">
          <p style="color: #999;">暂无早餐计划</p>
        </div>
      </Card>

      <!-- 午餐 -->
      <Card shadow class="meal-card lunch-card" style="margin-bottom: 20px;">
        <Row type="flex" justify="space-between" align="middle" style="margin-bottom: 15px;">
          <i-col>
            <h3 style="margin: 0;">
              <Icon type="md-sunny" size="24" style="margin-right: 10px; color: #f44336;"></Icon>
              <span>午餐</span>
              <Tag color="red" style="margin-left: 10px;">11:30 - 13:30</Tag>
            </h3>
          </i-col>
          <i-col>
            <Button type="primary" size="small" @click="showCreateMealModal('lunch')">添加午餐</Button>
          </i-col>
        </Row>
        <Divider style="margin: 15px 0;"></Divider>
        <div v-if="lunchMeals.length > 0" class="meals-list">
          <div v-for="meal in lunchMeals" :key="meal.id" class="meal-item">
            <MealCard :meal="meal" @edit="editMeal" @delete="deleteMeal"></MealCard>
          </div>
          <!-- 午餐统计 -->
          <div class="meal-summary">
            <Row :gutter="20">
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总热量：</span>
                  <span class="value">{{ lunchCalories }} kcal</span>
                </div>
              </i-col>
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总蛋白质：</span>
                  <span class="value">{{ lunchProtein }}g</span>
                </div>
              </i-col>
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总脂肪：</span>
                  <span class="value">{{ lunchFat }}g</span>
                </div>
              </i-col>
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总碳水：</span>
                  <span class="value">{{ lunchCarbs }}g</span>
                </div>
              </i-col>
            </Row>
          </div>
        </div>
        <div v-else class="empty-meal">
          <p style="color: #999;">暂无午餐计划</p>
        </div>
      </Card>

      <!-- 晚餐 -->
      <Card shadow class="meal-card dinner-card">
        <Row type="flex" justify="space-between" align="middle" style="margin-bottom: 15px;">
          <i-col>
            <h3 style="margin: 0;">
              <Icon type="md-moon" size="24" style="margin-right: 10px; color: #2196f3;"></Icon>
              <span>晚餐</span>
              <Tag color="blue" style="margin-left: 10px;">18:00 - 20:00</Tag>
            </h3>
          </i-col>
          <i-col>
            <Button type="primary" size="small" @click="showCreateMealModal('dinner')">添加晚餐</Button>
          </i-col>
        </Row>
        <Divider style="margin: 15px 0;"></Divider>
        <div v-if="dinnerMeals.length > 0" class="meals-list">
          <div v-for="meal in dinnerMeals" :key="meal.id" class="meal-item">
            <MealCard :meal="meal" @edit="editMeal" @delete="deleteMeal"></MealCard>
          </div>
          <!-- 晚餐统计 -->
          <div class="meal-summary">
            <Row :gutter="20">
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总热量：</span>
                  <span class="value">{{ dinnerCalories }} kcal</span>
                </div>
              </i-col>
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总蛋白质：</span>
                  <span class="value">{{ dinnerProtein }}g</span>
                </div>
              </i-col>
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总脂肪：</span>
                  <span class="value">{{ dinnerFat }}g</span>
                </div>
              </i-col>
              <i-col :xs="12" :sm="6">
                <div class="summary-item">
                  <span class="label">总碳水：</span>
                  <span class="value">{{ dinnerCarbs }}g</span>
                </div>
              </i-col>
            </Row>
          </div>
        </div>
        <div v-else class="empty-meal">
          <p style="color: #999;">暂无晚餐计划</p>
        </div>
      </Card>
    </div>

    <!-- 每日营养统计 -->
    <Card shadow style="margin-top: 20px;">
      <h3 style="margin-bottom: 15px;">每日营养统计</h3>
      <Row :gutter="20">
        <i-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-value">{{ totalDayCalories }}</div>
            <div class="stat-label">总热量 (kcal)</div>
            <Progress :percent="Math.min(totalDayCalories / 30, 100)" status="active"></Progress>
          </div>
        </i-col>
        <i-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-value">{{ totalDayProtein }}g</div>
            <div class="stat-label">总蛋白质</div>
            <Progress :percent="Math.min(totalDayProtein / 150, 100)" status="active"></Progress>
          </div>
        </i-col>
        <i-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-value">{{ totalDayFat }}g</div>
            <div class="stat-label">总脂肪</div>
            <Progress :percent="Math.min(totalDayFat / 80, 100)" status="active"></Progress>
          </div>
        </i-col>
        <i-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-value">{{ totalDayCarbs }}g</div>
            <div class="stat-label">总碳水化合物</div>
            <Progress :percent="Math.min(totalDayCarbs / 300, 100)" status="active"></Progress>
          </div>
        </i-col>
      </Row>
    </Card>

    <!-- 创建/编辑餐饮模态框 -->
    <Modal
      v-model="modalVisible"
      :title="isEdit ? '编辑餐饮' : '添加餐饮'"
      @on-ok="submitMeal"
      @on-cancel="resetModal"
      width="600"
    >
      <Form ref="mealForm" :model="formData" :rules="formRules" :label-width="100">
        <FormItem label="餐次" prop="mealType">
          <Select v-model="formData.mealType" placeholder="请选择餐次">
            <Option value="breakfast">早餐</Option>
            <Option value="lunch">午餐</Option>
            <Option value="dinner">晚餐</Option>
          </Select>
        </FormItem>

        <FormItem label="食物名称" prop="foodName">
          <Input
            v-model="formData.foodName"
            placeholder="请输入食物名称"
            maxlength="50"
          ></Input>
        </FormItem>

        <FormItem label="分量" prop="portion">
          <Input-Number
            v-model="formData.portion"
            :min="0.1"
            :max="10000"
            :step="0.1"
            placeholder="请输入分量"
          ></Input-Number>
          <span style="margin-left: 10px;">克</span>
        </FormItem>

        <FormItem label="热量(kcal)" prop="calories">
          <Input-Number
            v-model="formData.calories"
            :min="0"
            :max="5000"
            placeholder="请输入热量"
          ></Input-Number>
        </FormItem>

        <FormItem label="蛋白质(g)" prop="protein">
          <Input-Number
            v-model="formData.protein"
            :min="0"
            :max="1000"
            :step="0.1"
            placeholder="请输入蛋白质含量"
          ></Input-Number>
        </FormItem>

        <FormItem label="脂肪(g)" prop="fat">
          <Input-Number
            v-model="formData.fat"
            :min="0"
            :max="1000"
            :step="0.1"
            placeholder="请输入脂肪含量"
          ></Input-Number>
        </FormItem>

        <FormItem label="碳水(g)" prop="carbs">
          <Input-Number
            v-model="formData.carbs"
            :min="0"
            :max="1000"
            :step="0.1"
            placeholder="请输入碳水含量"
          ></Input-Number>
        </FormItem>

        <FormItem label="烹饪方式" prop="cookingMethod">
          <Select v-model="formData.cookingMethod" placeholder="请选择烹饪方式">
            <Option value="boil">煮</Option>
            <Option value="steam">蒸</Option>
            <Option value="fry">炒</Option>
            <Option value="deep_fry">炸</Option>
            <Option value="bake">烤</Option>
            <Option value="grill">烧烤</Option>
            <Option value="raw">生食</Option>
            <Option value="other">其他</Option>
          </Select>
        </FormItem>

        <FormItem label="食材" prop="ingredients">
          <Input
            v-model="formData.ingredients"
            type="textarea"
            :rows="3"
            placeholder="请输入食材，多个食材用逗号分隔，如：鸡肉,西兰花,胡萝卜"
            maxlength="200"
          ></Input>
        </FormItem>

        <FormItem label="备注" prop="notes">
          <Input
            v-model="formData.notes"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
            maxlength="100"
          ></Input>
        </FormItem>

        <FormItem label="提醒时间" prop="reminderTime">
          <TimePicker
            v-model="formData.reminderTime"
            format="HH:mm"
            placeholder="选择提醒时间"
            style="width: 100%;"
          ></TimePicker>
        </FormItem>

        <FormItem label="启用提醒">
          <i-switch v-model="formData.enableReminder"></i-switch>
          <span style="margin-left: 10px;">{{ formData.enableReminder ? '已启用' : '已禁用' }}</span>
        </FormItem>
      </Form>
    </Modal>

    <!-- 餐饮提醒弹窗 -->
    <Modal
      v-model="reminderModalVisible"
      title="餐饮提醒"
      @on-ok="dismissReminder"
      @on-cancel="dismissReminder"
      width="500"
    >
      <div class="reminder-content">
        <Alert type="info" style="margin-bottom: 15px;">
          <p>{{ reminderMessage }}</p>
        </Alert>
        <div v-if="currentReminderMeal" class="reminder-meal-info">
          <h4>{{ getMealTypeLabel(currentReminderMeal.mealType) }}食材信息：</h4>
          <Row :gutter="20" style="margin-top: 10px;">
            <i-col :xs="24" :sm="12">
              <strong>食物名称：</strong>
              <span>{{ currentReminderMeal.foodName }}</span>
            </i-col>
            <i-col :xs="24" :sm="12">
              <strong>分量：</strong>
              <span>{{ currentReminderMeal.portion }}g</span>
            </i-col>
            <i-col :xs="24" :sm="12">
              <strong>热量：</strong>
              <span>{{ currentReminderMeal.calories }}kcal</span>
            </i-col>
            <i-col :xs="24" :sm="12">
              <strong>烹饪方式：</strong>
              <span>{{ getCookingMethodLabel(currentReminderMeal.cookingMethod) }}</span>
            </i-col>
            <i-col :xs="24" :sm="12">
              <strong>食材：</strong>
              <span>{{ currentReminderMeal.ingredients }}</span>
            </i-col>
            <i-col v-if="currentReminderMeal.notes" :xs="24" :sm="12">
              <strong>备注：</strong>
              <span>{{ currentReminderMeal.notes }}</span>
            </i-col>
          </Row>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getMealPlans, createMealPlan, updateMealPlan, deleteMealPlan } from '@/api/plan'
import MealCard from './components/MealCard'
import reminderManager from '@/libs/reminder-manager'
import notificationService from '@/libs/notification-service'

export default {
  name: 'MealPlan',
  components: {
    MealCard
  },
  data () {
    return {
      loading: false,
      allMeals: [],
      selectedDate: new Date(),
      filterMealType: '',
      filterCalorieMin: 0,
      modalVisible: false,
      detailModalVisible: false,
      reminderModalVisible: false,
      isEdit: false,
      currentMealId: null,
      reminderMessage: '',
      currentReminderMeal: null,
      formData: {
        mealType: 'breakfast',
        foodName: '',
        portion: 100,
        calories: 0,
        protein: 0,
        fat: 0,
        carbs: 0,
        cookingMethod: 'steam',
        ingredients: '',
        notes: '',
        reminderTime: '',
        enableReminder: true
      },
      formRules: {
        mealType: [
          { required: true, message: '请选择餐次', trigger: 'change' }
        ],
        foodName: [
          { required: true, message: '请输入食物名称', trigger: 'blur' },
          { min: 1, max: 50, message: '食物名称长度应在1-50之间', trigger: 'blur' }
        ],
        portion: [
          { required: true, message: '请输入分量', trigger: 'blur' },
          { type: 'number', min: 0.1, message: '分量应大于0', trigger: 'blur' }
        ],
        calories: [
          { required: true, message: '请输入热量', trigger: 'blur' },
          { type: 'number', min: 0, message: '热量不能为负数', trigger: 'blur' }
        ],
        cookingMethod: [
          { required: true, message: '请选择烹饪方式', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    breakfastMeals () {
      return this.allMeals.filter(m => m.mealType === 'breakfast')
    },
    lunchMeals () {
      return this.allMeals.filter(m => m.mealType === 'lunch')
    },
    dinnerMeals () {
      return this.allMeals.filter(m => m.mealType === 'dinner')
    },
    breakfastCalories () {
      return this.breakfastMeals.reduce((sum, m) => sum + (m.calories || 0), 0)
    },
    breakfastProtein () {
      return this.breakfastMeals.reduce((sum, m) => sum + (m.protein || 0), 0).toFixed(1)
    },
    breakfastFat () {
      return this.breakfastMeals.reduce((sum, m) => sum + (m.fat || 0), 0).toFixed(1)
    },
    breakfastCarbs () {
      return this.breakfastMeals.reduce((sum, m) => sum + (m.carbs || 0), 0).toFixed(1)
    },
    lunchCalories () {
      return this.lunchMeals.reduce((sum, m) => sum + (m.calories || 0), 0)
    },
    lunchProtein () {
      return this.lunchMeals.reduce((sum, m) => sum + (m.protein || 0), 0).toFixed(1)
    },
    lunchFat () {
      return this.lunchMeals.reduce((sum, m) => sum + (m.fat || 0), 0).toFixed(1)
    },
    lunchCarbs () {
      return this.lunchMeals.reduce((sum, m) => sum + (m.carbs || 0), 0).toFixed(1)
    },
    dinnerCalories () {
      return this.dinnerMeals.reduce((sum, m) => sum + (m.calories || 0), 0)
    },
    dinnerProtein () {
      return this.dinnerMeals.reduce((sum, m) => sum + (m.protein || 0), 0).toFixed(1)
    },
    dinnerFat () {
      return this.dinnerMeals.reduce((sum, m) => sum + (m.fat || 0), 0).toFixed(1)
    },
    dinnerCarbs () {
      return this.dinnerMeals.reduce((sum, m) => sum + (m.carbs || 0), 0).toFixed(1)
    },
    totalDayCalories () {
      return this.allMeals.reduce((sum, m) => sum + (m.calories || 0), 0)
    },
    totalDayProtein () {
      return this.allMeals.reduce((sum, m) => sum + (m.protein || 0), 0).toFixed(1)
    },
    totalDayFat () {
      return this.allMeals.reduce((sum, m) => sum + (m.fat || 0), 0).toFixed(1)
    },
    totalDayCarbs () {
      return this.allMeals.reduce((sum, m) => sum + (m.carbs || 0), 0).toFixed(1)
    }
  },
  mounted () {
    this.loadMeals()
    this.initReminders()
  },
  beforeDestroy () {
    // 清理所有定时器
    reminderManager.clearAllReminders()
  },
  methods: {
    loadMeals () {
      this.loading = true
      // 模拟加载数据，实际使用API
      setTimeout(() => {
        this.allMeals = [
          {
            id: 1,
            mealType: 'breakfast',
            foodName: '鸡蛋羹',
            portion: 100,
            calories: 155,
            protein: 13,
            fat: 11,
            carbs: 1.1,
            cookingMethod: 'steam',
            ingredients: '鸡蛋,盐,油',
            notes: '营养丰富',
            reminderTime: '07:00',
            enableReminder: true
          },
          {
            id: 2,
            mealType: 'breakfast',
            foodName: '牛奶燕麦',
            portion: 200,
            calories: 150,
            protein: 5,
            fat: 3,
            carbs: 27,
            cookingMethod: 'boil',
            ingredients: '燕麦,牛奶,蜂蜜',
            notes: '早上消化易',
            reminderTime: '07:00',
            enableReminder: true
          },
          {
            id: 3,
            mealType: 'lunch',
            foodName: '清蒸鱼',
            portion: 150,
            calories: 195,
            protein: 25,
            fat: 10,
            carbs: 0,
            cookingMethod: 'steam',
            ingredients: '鱼肉,葱,姜,盐',
            notes: '低脂蛋白',
            reminderTime: '12:00',
            enableReminder: true
          },
          {
            id: 4,
            mealType: 'lunch',
            foodName: '糙米饭',
            portion: 150,
            calories: 195,
            protein: 4,
            fat: 1.5,
            carbs: 43,
            cookingMethod: 'boil',
            ingredients: '糙米,水,盐',
            notes: '纤维丰富',
            reminderTime: '12:00',
            enableReminder: true
          },
          {
            id: 5,
            mealType: 'lunch',
            foodName: '西兰花',
            portion: 100,
            calories: 34,
            protein: 3.7,
            fat: 0.4,
            carbs: 7,
            cookingMethod: 'steam',
            ingredients: '西兰花,盐',
            notes: '维生素丰富',
            reminderTime: '12:00',
            enableReminder: true
          },
          {
            id: 6,
            mealType: 'dinner',
            foodName: '番茄鸡蛋汤',
            portion: 300,
            calories: 120,
            protein: 10,
            fat: 5,
            carbs: 8,
            cookingMethod: 'boil',
            ingredients: '番茄,鸡蛋,青菜,盐',
            notes: '清淡易消化',
            reminderTime: '18:00',
            enableReminder: true
          },
          {
            id: 7,
            mealType: 'dinner',
            foodName: '鸡胸肉沙拉',
            portion: 200,
            calories: 240,
            protein: 35,
            fat: 8,
            carbs: 5,
            cookingMethod: 'bake',
            ingredients: '鸡胸肉,生菜,番茄,黄瓜',
            notes: '高蛋白低脂',
            reminderTime: '18:00',
            enableReminder: true
          }
        ]
        this.loading = false
        // 重新初始化提醒
        this.initReminders()
      }, 500)
    },
    initReminders () {
      // 初始化提醒管理器
      if (!reminderManager.callback) {
        reminderManager.init((meal) => {
          this.showMealReminder(meal)
        })
      }
      
      // 设置所有启用提醒的餐饮
      const remindableMeals = this.allMeals.filter(m => m.enableReminder && m.reminderTime)
      reminderManager.setReminders(remindableMeals)
    },
    showMealReminder (meal) {
      this.currentReminderMeal = meal
      const mealTypeLabel = this.getMealTypeLabel(meal.mealType)
      this.reminderMessage = `亲爱的用户，现在是${mealTypeLabel}时间，建议您享用${meal.foodName}！`
      this.reminderModalVisible = true

      // 同时发送站内信
      this.sendMealReminderMessage(meal)

      // 自动弹窗持续时间 - 30秒后自动关闭
      setTimeout(() => {
        this.reminderModalVisible = false
      }, 30000)
    },
    dismissReminder () {
      this.reminderModalVisible = false
    },
    async sendMealReminderMessage (meal) {
      // 发送站内信提醒
      const mealTypeLabel = this.getMealTypeLabel(meal.mealType)
      const success = await notificationService.sendMealReminder(meal, mealTypeLabel)
      
      if (success) {
        this.$Message.success('餐饮提醒消息已发送')
      } else {
        // 如果发送失败，将消息加入队列
        const message = {
          title: `${mealTypeLabel}提醒`,
          content: `现在是${mealTypeLabel}时间！建议您享用：${meal.foodName}（${meal.portion}g，${meal.calories}kcal）`,
          type: 'meal_reminder'
        }
        notificationService.queueMessage(message)
      }
    },
    onDateChange () {
      this.loadMeals()
    },
    searchMeals () {
      // 根据条件筛选
      this.$Message.success('已查询餐饮计划')
    },
    resetFilter () {
      this.filterMealType = ''
      this.filterCalorieMin = 0
      this.loadMeals()
    },
    showCreateModal () {
      this.isEdit = false
      this.resetModal()
      this.modalVisible = true
    },
    showCreateMealModal (mealType) {
      this.isEdit = false
      this.resetModal()
      this.formData.mealType = mealType
      this.modalVisible = true
    },
    editMeal (meal) {
      this.isEdit = true
      this.currentMealId = meal.id
      this.formData = { ...meal }
      this.modalVisible = true
    },
    submitMeal () {
      this.$refs.mealForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            updateMealPlan(this.currentMealId, this.formData).then(() => {
              this.$Message.success('餐饮计划更新成功')
              this.modalVisible = false
              this.loadMeals()
              // 如果启用了提醒，重新设置提醒
              if (this.formData.enableReminder && this.formData.reminderTime) {
                const updatedMeal = { ...this.formData, id: this.currentMealId }
                reminderManager.updateReminder(this.currentMealId, updatedMeal)
              } else {
                reminderManager.clearReminder(this.currentMealId)
              }
            }).catch(() => {
              this.$Message.error('餐饮计划更新失败')
            })
          } else {
            createMealPlan(this.formData).then(() => {
              this.$Message.success('餐饮计划创建成功')
              this.modalVisible = false
              this.loadMeals()
              // 如果启用了提醒，设置提醒
              if (this.formData.enableReminder && this.formData.reminderTime) {
                const newMeal = { id: Math.random(), ...this.formData }
                reminderManager.setReminder(newMeal)
              }
            }).catch(() => {
              this.$Message.error('餐饮计划创建失败')
            })
          }
        }
      })
    },
    resetModal () {
      this.formData = {
        mealType: 'breakfast',
        foodName: '',
        portion: 100,
        calories: 0,
        protein: 0,
        fat: 0,
        carbs: 0,
        cookingMethod: 'steam',
        ingredients: '',
        notes: '',
        reminderTime: '',
        enableReminder: true
      }
      this.$refs.mealForm && this.$refs.mealForm.resetFields()
    },
    deleteMeal (id) {
      this.$Modal.confirm({
        title: '删除餐饮',
        content: '确定要删除这个餐饮计划吗？',
        okText: '删除',
        cancelText: '取消',
        onOk: () => {
          deleteMealPlan(id).then(() => {
            this.$Message.success('餐饮计划删除成功')
            // 清除该餐饮的提醒
            reminderManager.clearReminder(id)
            this.loadMeals()
          }).catch(() => {
            this.$Message.error('餐饮计划删除失败')
          })
        }
      })
    },
    getMealTypeLabel (type) {
      const typeMap = {
        breakfast: '早餐',
        lunch: '午餐',
        dinner: '晚餐'
      }
      return typeMap[type] || type
    },
    getCookingMethodLabel (method) {
      const methodMap = {
        boil: '煮',
        steam: '蒸',
        fry: '炒',
        deep_fry: '炸',
        bake: '烤',
        grill: '烧烤',
        raw: '生食',
        other: '其他'
      }
      return methodMap[method] || method
    }
  }
}
</script>

<style scoped lang="less">
.meal-plan-container {
  .meal-card {
    &.breakfast-card {
      border-top: 4px solid #ff9800;
    }
    &.lunch-card {
      border-top: 4px solid #f44336;
    }
    &.dinner-card {
      border-top: 4px solid #2196f3;
    }
  }

  .meals-list {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-bottom: 15px;

    .meal-item {
      flex: 1;
      min-width: 300px;
      max-width: 100%;
    }
  }

  .meal-summary {
    background: #f5f5f5;
    padding: 15px;
    border-radius: 4px;
    margin-top: 15px;

    .summary-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 0;

      .label {
        color: #666;
        font-weight: 500;
      }

      .value {
        color: #2d8cf0;
        font-weight: bold;
      }
    }
  }

  .empty-meal {
    text-align: center;
    padding: 20px;
    color: #999;
  }

  .stat-card {
    background: #f5f5f5;
    padding: 15px;
    border-radius: 4px;
    text-align: center;

    .stat-value {
      font-size: 28px;
      color: #2d8cf0;
      font-weight: bold;
      margin-bottom: 5px;
    }

    .stat-label {
      color: #666;
      font-size: 12px;
      margin-bottom: 10px;
    }
  }

  .reminder-content {
    .reminder-meal-info {
      background: #f9f9f9;
      padding: 15px;
      border-radius: 4px;
      border-left: 3px solid #2d8cf0;

      h4 {
        margin-top: 0;
        color: #333;
      }

      strong {
        color: #666;
        display: inline-block;
        width: 100px;
      }

      span {
        color: #333;
      }
    }
  }
}
</style>
